﻿/******************************************************************************
* File description: downloadManager.cpp
* Function: 从https服务器下载文件
* Current Version: 1.0.0
* Author: JNN
* Date: 2025-07-01
*  -----
*  Copyright by 博坤生物 .
 *****************************************************************************/


#include "downloadManager.h"

/** @brief 构造函数 */
DownloadManager::DownloadManager()
{

}

/** @brief 单例函数 */
DownloadManager& DownloadManager::I(){

    static DownloadManager instance;
    return instance;
}

/** @brief 从服务器下载文件
 *  @param url 服务器地址
 *  @param localPath 本地地址
 *  @param 是否阻塞
 *  @return int -1失败 0成功 */
int DownloadManager::downloadFile(QString url, QString localPath, bool block){

    qDebug() << "block：" << block;


    file.setFileName(localPath);
    if(!file.open(QIODevice::WriteOnly)){
        qDebug() << "本地存储路径无效";
        return -2;
    }

    isDownloading = true;

    int timeout = 10000;

    QNetworkAccessManager networkManager;
    QNetworkRequest request;
    request.setUrl(QUrl(url));
    QNetworkReply *reply = networkManager.get(request);
    QTimer timer;
    QEventLoop eventLoop;
    connect(reply, &QNetworkReply::downloadProgress, [=, &timer](qint64 bytesReceived,qint64 bytesTotal){
        qDebug()<<"当前下载的文件大小："<<bytesReceived<<"   总文件大小："<<bytesTotal;
        if (timer.isActive())
            timer.start(timeout);
        file.write(reply->readAll());
    });
    connect(reply, &QNetworkReply::finished, this, &DownloadManager::onDownloadFinished);
    connect(reply, &QNetworkReply::finished, &eventLoop, &QEventLoop::quit);
    eventLoop.exec();//QEventLoop::ExcludeUserInputEvents
    if (reply->error() != QNetworkReply::NoError)
    {
        qDebug()<<"请求失败！失败原因："<<reply->error();
        file.close();
        delete reply;
        return -1;
    }
    qDebug() << "block：" << block;



    if(block){
        qDebug() << "阻塞开始";
        while (1) {
            if(isDownloading == false){
                qDebug() << "阻塞中断";
                break;
            }
            Sleep(100);
        }
    }

    return 0;

}

/** @brief 下载完成后触发的槽函数 */
void DownloadManager::onDownloadFinished(){

    qDebug() << "下载完成（大概吧）";
    isDownloading = false;
    file.close();

}
